import typeOfUtils from "./type-of-utils";
import {deepClone} from "./index";

export type RuleCallBack = (err?: Error) => void

export interface Rule {
  required?: boolean;
  message?: string;
  validatorAsync?: (rule: Rule, value: any) => void | Error | Promise<string>;
  validator?: (rule: Rule, value: any, callback: RuleCallBack) => void
  trigger?: 'blur' | 'change';
  min?: number;
  max?: number;
}


export interface Rules {
  [key: string]: Rule[]
}

export class ElFormUtils {
  /**
   * 检验为改同步化写法
   * @param value
   */
  public static rulesPlus<T extends Rules>(value: T): Required<T> {
    const result = {}
    Object.keys(value).forEach(key => {
      result[key] = value[key].map(i => {
        const item = deepClone(i)
        if (i.validatorAsync) {
          item.validator = (rule, value, callback) => {
            // @ts-ignore
            const res = i.validatorAsync(rule, value)
            if (typeOfUtils.isPromise(res)) {
              (res as Promise<string>).then(r => {
                callback()
              }).catch(e => {
                callback(new Error(e))
              })
            } else if (typeOfUtils.isError(res)) {
              callback(res as Error)
            } else {
              callback()
            }
          }
        }
        return item
      })
    })
    return result as Required<T>
  }
}
